import os
from multiprocessing.dummy import Pool as ThreadPool
import requests
import multiprocessing
from you_get import common

global output_dir_down

def process_down(url):
    # print(url)
    common.any_download(url=url, info_only=False, output_dir=output_dir_down, merge=True,ext="mp4")


def url_all_list(parent_url, total):
    url_list = []
    if total > 1:
        total = total + 1
        for i in range(1, total):
            url = "{}?p={}".format(parent_url, i)
            url_list.append(url)
    if total == 1:
        url_list.append(parent_url)
    return url_list


def get_video_count(url):
    headers  ={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4302.0 Safari/537.36'}
    req = requests.get(url,headers =headers ).text
    start_with = req.find('videos')
    end_with = req.find(',"tid')
    result = req[start_with:end_with]
    video_count = result.split(":")[1]
    return video_count;


if __name__ == "__main__":
    multiprocessing.freeze_support()
    # 视频url地址
    bv_num = input("请输入BV号 (例如：BV1aW41187Qw ) ：")
    output_dir_down = input("输出目录为： ")
    parent_url = "https://www.bilibili.com/video/{}".format(bv_num)
    parallel_count = int(input("需要同时几个文件同时下载 (建议1 - 10 之间)："))
    if parallel_count < 1 and parallel_count > 100 :
        parallel_count=1
    # 视频总数量
    total = int(get_video_count(parent_url))
    print("当前视频总数量：",total)
    file_list = url_all_list(parent_url, total)
    print("当前并行数量：",parallel_count)
    pool = ThreadPool(parallel_count)
    pool.map(process_down, file_list)
    pool.close()
    pool.join()

